package com.bdqn.controller;

import com.alibaba.fastjson.JSON;
import com.bdqn.constant.Constant;
import com.bdqn.pojo.PageSupport;
import com.bdqn.pojo.SysRole;
import com.bdqn.pojo.SysUser;

import com.bdqn.service.SysRoleService;
import com.bdqn.service.SysUserService;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/**/user")
public class SysUserController {
    private Logger logger = Logger.getLogger(SysUserController.class);

    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysRoleService sysRoleService;

    //跳转到登录页面
    @RequestMapping("/toLogin")
    public String login() {
        logger.debug("跳转到登录页面");
        return "login";
    }

    //登录
    @PostMapping("/login")
    public String doLogin(@RequestParam String account, @RequestParam String password, HttpServletRequest request, HttpSession session) {
        logger.debug("进入登录方法");
        System.out.println("账号：" + account + "\n密码：" + password);
        //调用Service方法，进行用户匹配
        SysUser sysUser = sysUserService.login(account, password);
        if (null != sysUser) {
            //将登录用户放入session
            session.setAttribute(Constant.USER_SESSION, sysUser);
            //登录成功，重定向到/user/toMain接口
            return "redirect:/user/toMain";
        } else {
            //页面跳转（login.jsp）带出提示信息--转发
            request.setAttribute("error", "用户名或密码不正确");
            //用户不存在，登录失败，跳转到登录页面
            return "login";
        }
    }

    //跳转到首页
    @RequestMapping("/toMain")
    public String main(HttpSession session) {
        if (session.getAttribute(Constant.USER_SESSION) == null) {
            //重定向到登录页面接口
            return "redirect:/user/toLogin";
        }
        return "frame";
    }

//    捕获异常信息，跳转到error页面
//    @ExceptionHandler(value = {RuntimeException.class})
//    public String handlerException(RuntimeException e, HttpServletRequest req){
//        req.setAttribute("e",e);
//        return "error";
//    }

    //一个抛出异常的接口
    @RequestMapping("/exLogin")
    public String exLogin(@RequestParam String account,@RequestParam String password){
        SysUser user = sysUserService.login(account,password);
        if (null == user){
            throw new RuntimeException("用户名或者密码不正确！");
        }
        return "redirect:/user/toMain";
    }

    @GetMapping("/list")
    public String getUserList(Model model, @RequestParam(value = "realName", required = false) String queryRealName, @RequestParam(value = "roleId", required = false) Integer queryRoleId, @RequestParam(defaultValue = "1") Integer pageIndex) {
        List<SysUser> userList = null;
        try {
            //设置页面容量
            int pageSize = Constant.pageSize;
            //总数量(表)
            int totalCount = sysUserService.getUserCount(queryRealName, queryRoleId);
            //总页数
            PageSupport pages = new PageSupport();
            pages.setCurrentPageNo(pageIndex);
            pages.setPageSize(pageSize);
            pages.setTotalCount(totalCount);
            int totalPageCount = pages.getTotalPageCount();
            //控制首页和尾页
            if (pageIndex > totalPageCount) {
                pageIndex = totalPageCount;
                throw new RuntimeException("页码不正确");
            }
            userList = sysUserService.getUserList(queryRealName, queryRoleId, pageIndex, pageSize);
            model.addAttribute("userList", userList);
            List<SysRole> roleList = sysUserService.getRoleList();
            model.addAttribute("roleList", roleList);
            model.addAttribute("realName", queryRealName);
            model.addAttribute("roleId", queryRoleId);
            model.addAttribute("page", pages);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("用户列表接口访问失败" + e);
//            return "redirect:/user/toSysError";
        }
        return "sysUser/list";
    }

    //跳转到异常处理页面
//    @RequestMapping(value = "/toSysError")
//    public String sysError() {
//        return "sysError";
//    }

    //退出登录
    @RequestMapping("/logout")
    public String logout() {
        return "login";
    }

    //跳转到添加用户页面
    @RequestMapping("/toAdd")
    public String toAdd(Model model) {
        List<SysRole> roleList = sysUserService.getRoleList();
        model.addAttribute("roleList", roleList);
        return "sysUser/add";
    }

    @PostMapping("/add")
    public String add(Model model, SysUser sysUser, HttpSession session, HttpServletRequest request, @RequestParam(value = "attachs", required = false) MultipartFile[] attachs) {
        // 证件照路径
        String idPicPath = null;
        // 工作证照片路径
        String workPicPath = null;
        // 错误信息
        String errorInfo = null;
        boolean flag = true;
        // 文件的存储位置
        String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
        logger.info("文件的存储路径:" + path);
        for (int i = 0; i < attachs.length; i++) {
            // 获取单独的上传照片对象
            MultipartFile attach = attachs[i];
            if (!attach.isEmpty()) {
                if (i == 0) {
                    // 异常信息
                    errorInfo = "uploadFileError";
                } else if (i == 1) {
                    errorInfo = "uploadWpError";
                }
                String oldFileName = attach.getOriginalFilename(); // 原来的文件名
                logger.info("原来的文件名:" + oldFileName); // 原文件后缀
                String prefix = FilenameUtils.getExtension(oldFileName); // 使用FilenameUtils工具类提取文件名的后缀
                logger.debug("原文件后缀:" + prefix);
                int filesize = 5000000;
                logger.debug("上传文件大小:" + attach.getSize());
                if (attach.getSize() > filesize) { // 上传大小不得超过500 KB
                    request.setAttribute(errorInfo, " * 上传大小不得超过 500 KB");
                    flag = false;
                } else if (prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png") || prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")) {
                    // 文件名的重组:系统的时间戳+随机数+_Personal.+原来的后缀
                    String fileName = System.currentTimeMillis() + RandomUtils.nextInt(0, 1000000) + "_Personal." + prefix;
                    File targerFile = new File(path);
                    // 判断路径下的文件是否存在
                    if (!targerFile.exists()) {
                        // 不存在则创建
                        targerFile.mkdirs();
                    }
                    // 保存

                    try {
                        // 文件传输
                        attach.transferTo(new File(targerFile, fileName));
                    } catch (IOException e) {
                        e.printStackTrace();
                        request.setAttribute(errorInfo, " * 上传失败!");
                        flag = false;
                    }
                    if (i == 0) {
                        idPicPath = File.separator + "statics" + File.separator + "uploadfiles" + File.separator + fileName;
                    } else {
                        workPicPath = File.separator + "statics" + File.separator + "uploadfiles" + File.separator + fileName;
                    }
                    logger.debug("idPicPath" + idPicPath);
                    logger.debug("workPicPath" + workPicPath);
                } else {
                    request.setAttribute("errorInfo", " * 上传图片格式不正确");
                    flag = false;
                }
            }
        }
        if (flag) {
            sysUser.setCreatedUserId(((SysUser) session.getAttribute(Constant.USER_SESSION)).getId());
            sysUser.setCreatedTime(new Date());
            sysUser.setIdPicPath(idPicPath);
            sysUser.setWorkPicPath(workPicPath);
            if (sysUserService.add(sysUser)) {
                return "redirect:/user/list";
            }
            sysUser.setCreatedUserId(((SysUser) session.getAttribute(Constant.USER_SESSION)).getId());
            if (sysUserService.add(sysUser)) {
                return "redirect:/user/list";
            }
        }
        return "sysUser/add";
    }

    //查询用户详情
    @GetMapping("/view/{id}")
    //@GetMapping("/{id}")
    //@GetMapping("/{id}/view")
    public Object view(@PathVariable String id, Model model) {
        logger.debug("根据Id查询用户详情" + id);
        SysUser sysUser = sysUserService.getUserById(id);
        model.addAttribute(sysUser);
        return "sysUser/view";
    }

    @GetMapping("/toUpdate")
    public String toUpdate(@RequestParam("uid") String uid, Model model) {
        logger.debug("跳转到修改用户信息页面" + uid + "\n");
        List<SysRole> roleList = sysRoleService.getRole();
        SysUser sysUser = sysUserService.getUserById(uid);
        model.addAttribute("roleList",roleList);
        model.addAttribute("sysUser",sysUser);
        return "sysUser/update";
    }

    //修改用户信息
    @PostMapping("/update")
    public String update(SysUser sysUser, HttpSession session) {
        logger.debug("修改用户信息");
        sysUser.setUpdatedUserId(((SysUser) session.getAttribute(Constant.USER_SESSION)).getId());
        sysUser.setUpdatedTime(new Date());
        if (sysUserService.update(sysUser) > 0) {
            return "redirect:/user/list";
        }
        return "sysUser/update";
    }

    /**
     * 查重
     * @param account
     * @return
     */
    @ResponseBody
    @GetMapping("/userExist")
    public Object userExist(@RequestParam("account") String account){
        logger.debug("验证用户名account="+account+"的用户是否存在");
        HashMap<String,Object> resultMap = new HashMap<String,Object>();
        if (StringUtils.isEmpty(account)){
            resultMap.put("exist",1);
        }else{
            SysUser sysUser = sysUserService.getAccountExist(account);
            if (null!=sysUser){
                resultMap.put("exist",1);
            }else{
                resultMap.put("exist",0);
            }
        }
        return JSON.toJSONString(resultMap);
    }

    @RequestMapping("/toUpdatePwd")
    public String toUpdatePassword(){
        return "sysUser/updatePassword";
    }

    /**
     * 旧密码查重
     * @param session
     * @param oldPassword
     * @return
     */
    @ResponseBody
    @RequestMapping("/checkOldPwd")
    public Object checkOldPwd(HttpSession session,@RequestParam("oldPassword") String oldPassword) {
        logger.debug("旧密码：" + oldPassword);

        //原密码
        String pwd = ((SysUser) session.getAttribute(Constant.USER_SESSION)).getPassword();
        logger.debug("原密码：" + pwd);
        HashMap<String, Object> resultMap = new HashMap<String, Object>();
        if (oldPassword != null) {
            if (pwd != null) {
                if (oldPassword.equals(pwd)) {
                    resultMap.put("result", "true");
                } else {
                    resultMap.put("result","false");
                }
            } else {
                resultMap.put("result", "sessionerror");
            }
        }else{
            resultMap.put("result", "error");
        }
        return JSON.toJSONString(resultMap);
    }

    @PostMapping("/savePassword")
    public String savePassword(HttpSession session,@RequestParam("newPassword")String newPassword){
        logger.debug("新密码：" + newPassword);
        //获得ID
        Integer id = ((SysUser)session.getAttribute(Constant.USER_SESSION)).getId();
        if (sysUserService.savePwd(newPassword,id)){
            //这个方法将从 session 中删除指定的属性
            session.removeAttribute(Constant.USER_SESSION);
            return "redirect:user/toLogin";
        }
        return "sysUser/updatePassword";
    }

    @ResponseBody
    @RequestMapping("/del/{uid}")
    public Object del(@PathVariable String uid){
        logger.debug("进入删除方法");
        HashMap<String,Object> resultMap = new HashMap<String,Object>();
        logger.debug("获取id:" + uid);

        if (sysUserService.delete(Integer.valueOf(uid))){
            resultMap.put("delResult","true");
        }else {
            resultMap.put("delResult","false");
        }
        return JSON.toJSONString(resultMap);
    }

//    @RequestMapping("/logout")
//    public String logout(){
//        return "login";
//    }
}
